﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ExtensibleEventViewer.Console.DomainModel;
using ExtensibleEventViewer.Core.Interfaces;


namespace ExtensibleEventViewer.Console.Forms
{
	public partial class SettingsWnd : FormBase
	{
		private readonly IEnumerable<IEventLogFilter> _eventLogFilters;
		private readonly KeyValuePair<string, bool>[] _filterStatuses;

		/// <summary>
		/// Initializes form instance
		/// </summary>
		public SettingsWnd(IEnumerable<IEventLogFilter> availableEventLogFilters, KeyValuePair<string, bool>[] filterStatuses)
		{
			InitializeComponent();

			_eventLogFilters = availableEventLogFilters;
			_filterStatuses = filterStatuses;
		}

		private void menuItemOpenSettings_Click(object sender, EventArgs e)
		{
			Control configControl = ((IEventLogFilter) clbEnabledFilters.SelectedItem).ConfigurationControl;

			using (FilterSettingsWnd filterSettingsWnd = new FilterSettingsWnd(configControl))
			{
				filterSettingsWnd.ShowDialog(this);
			}
		}

		/// <summary>
		/// Raises the <see cref="E:System.Windows.Forms.Form.Load"/> event.
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		protected override void OnLoad(EventArgs e)
		{
			foreach (IEventLogFilter filter in _eventLogFilters)
			{
				bool isEnabled = (from enabledFilter in _filterStatuses
				                 where enabledFilter.Key == filter.FilterID
				                 select enabledFilter.Value).FirstOrDefault();


				clbEnabledFilters.Items.Add(filter, isEnabled);
			}
			
			base.OnLoad(e);
		}

		private void menuOpenFilterSettings_Opening(object sender, CancelEventArgs e)
		{
			Point mousePosition = MousePosition;
			int index = clbEnabledFilters.IndexFromPoint(clbEnabledFilters.PointToClient(mousePosition));

			if (index != -1)
			{
				clbEnabledFilters.SetSelected(index, true);
			}
			else
			{
				e.Cancel = true;
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			ListBox.SelectedObjectCollection selectedFilters = clbEnabledFilters.SelectedItems;
			List<KeyValuePair<string,bool>> enabledFilters = new List<KeyValuePair<string, bool>>();

			foreach (IEventLogFilter filter in selectedFilters)
			{
				enabledFilters.Add(new KeyValuePair<string, bool>(filter.FilterID, true));
			}

			AppSettings.Instance.EnabledEventLogFilters = enabledFilters.ToArray();

			Close();
		}
	}
}
